layui.define(['jquery', 'layer','upload'], function(exports) {
    "use strict";
    // 声明变量
    var $ = layui.$;
    var layer = layui.layer;
    var table_id='layer-table-list';
    var upload = layui.upload;

    // 声明类
    var layCenter = {

        limit: 10,
        limits: [10,20,30,40,50],

        /**
         * 先关闭然后刷新父页面
         * @param tableid
         */
        CloseLayerReload: function() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
            parent.layui.table.reload(table_id, 'data');
        },

        /**
         * 关闭父级页面不刷新
         */
        CloseLayer: function() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },

        /**
         * //先刷新父页面后关闭
         */
        CloseFa: function() {
            parent.location.reload();
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },

        /**
         * 表格重载
         * @constructor
         */
        CreateReload: function() {
            layui.table.reload(table_id, { where: {} }, 'data');
        },

        /**
         * form表单提交
         * @param url   提交地址
         * @param data  表单数据
         * @param reload 关闭弹窗刷新父页面的表格
         * @param cloeFa 关闭弹窗刷新父页面
         * @constructor
         */
        FormSubmit: function(url, data, reload, cloeFa) {
            $.ajax({
                url: url,
                type: 'post',
                data: data,
                error: function(error) {
                    var json = JSON.parse(error.responseText);
                    $.each(json.errors, function(idx, obj) {
                        layer.msg(obj[0], { icon: 15, time: 1500, shade: 0.3, anim: 4 });
                        return false;
                    });
                },
                beforeSend: function() {
                    layer.load(2);
                },
                success: function(res) {
                    console.log(res);
                    if(res.code === 1){
                        if($.common.isNotEmpty(reload)){
                            layer.msg(res.msg, { icon: 1, time: 1000, shade: 0.3, anim: 4 }, function(){
                                layCenter.CloseLayerReload(table_id); //重载父页面表格
                            });
                        } else if($.common.isNotEmpty(cloeFa)) {
                            layer.msg(res.msg, { icon: 1, time: 1000, shade: 0.3, anim: 4 }, function(){
                                layCenter.CloseLayer(table_id); //关闭弹窗
                            });
                        } else {
                            layer.msg(res.msg, { icon: 1, time: 1500, shade: 0.3, anim: 4 }, function() {
                                window.location.reload();
                            });
                        }
                    } else if(res.code == 2){
                        layer.msg(res.msg, { icon: 15, time: 1500, shade: 0.3, anim: 4 }, function() {
                            layCenter.JumpLogin();
                        });
                    } else {
                        layer.msg(res.msg, { icon: 15, time: 1500, shade: 0.3, anim: 4 });
                    }
                },
                complete: function() {
                    layer.closeAll('loading');
                }
            });
        },

        /**
         *
         * @param title 标题
         * @param url 地址
         * @param w  宽
         * @param h  高
         * @param is_full 最大化
         * @constructor
         */
        CreateOpenForm: function(title, url, w, h, is_full) {
            if ($.common.isMobile()) {
                w = 'auto';
                h = 'auto';
            }else {
                w=$.common.isNotEmpty(w)?w:'60%';
                h=$.common.isNotEmpty(h)?h:'80%';
            }
            if ($.common.isEmpty(url)) {
                url = "/404.html";
            }
            var full = layer.open({
                title: title,
                type: 2,
                area: [w, h],
                offset: 'auto',
                maxmin: true,
                zIndex: layer.zIndex,
                shade: 0.5,
                content: url,
                btn: ['保存', '取消'],
                yes: function(index, layero){
                    //点击确认触发 iframe 内容中的按钮提交
                    var submit = layero.find('iframe').contents().find("#layui-btn-form-submit");
                    submit.click();
                }
            });
            if ($.common.isNotEmpty(is_full)){
                layer.full(full); //最大化
            }
        },

        /**
         * 弹窗随机动画
         * @param Anim
         * @returns {string|number}
         */
        randomAnim: function(Anim = "7") {
            var animArray = ["0", "1", "2", "3", "4", "5", "6"];
            if ($.inArray(Anim, animArray)) {
                return Anim;
            } else {
                return Math.floor(Math.random() * animArray.length);
            }
        },
        /**
         * 随机图标
         * @returns {number}
         */
        randomIcon: function() {
            // 绿色勾,红色叉,黄色问号,灰色锁,红色哭脸,绿色笑脸,黄色感叹号
            var iconArray = [1, 2, 3, 4, 5, 6, 7];
            return Math.floor(Math.random() * iconArray.length);
        },

        /**
         * 随机layui 弹窗皮肤颜色
         * @returns {string}
         */
        randomSkin: function(yan = "jrk") {
            var skinArray = ["", "layui-layer-molv", "layui-layer-lan"];
            if ($.inArray(yan, skinArray)) {
                return yan;
            } else {
                return skinArray[Math.floor(Math.random() * skinArray.length)];
            }
        },

        /**
         * layer-msg
         * @param msg
         * @param icon
         * @param callbackFunction
         */
        layerMsg: function(msg, icon, callbackFunction) {
            //1-绿色勾,2-红色叉,3-黄色问号,4-灰色锁,5-红色哭脸,6-绿色笑脸,7-黄色感叹号,15-返回失败
            let options = { icon: icon || layCenter.randomIcon(), time: 1500, shade: 0.4, anim: layCenter.randomAnim() };
            layer.msg(msg, options, callbackFunction);
        },

        /**
         * 数据异步提交
         * @param url
         * @param data
         * @param reload
         * @constructor
         */
        Ajax: function(url, data, reload ) {
            $.ajax({
                beforeSend: function() {
                    layer.load(2);
                },
                url: url,
                type: "POST",
                async: true,
                dataType: "json",
                data: data,
                error: function(error) {
                    layer.msg("服务器错误或超时");
                    return false;
                },
                success: function(res) {
                    if (res.code == 1) {
                        layCenter.layerMsg(res.msg, 1, function() {
                            if ($.common.isNotEmpty(reload)) {
                                window.location.reload();
                            } else {
                                layCenter.CreateReload(table_id); //重载表格
                            }
                        });
                    } else if(res.code == 2){
                        layer.msg(res.msg, { icon: 15, time: 1500, shade: 0.3, anim: 4 }, function() {
                            layCenter.JumpLogin();
                        });
                    } else {
                        layer.msg(res.msg, { icon: 15, time: 1000, shade: 0.3 });
                    }
                },
                complete: function() {
                    layer.closeAll('loading');
                }
            });
        },

        /**
         * 根据id删除数据并且重载table
         * @param url 请求地址
         * @param id 需要删除的数据的id (批量删除时为数组)
         * @param batch
         * @constructor
         */
        DelByIds: function(url, id, batch = false){
            if(!id){
                layer.msg('ID不能为空', { icon: 15, time: 1000, shade: 0.3 });
                return false;
            }
            if(batch && id.length <= 0){
                layer.msg('请勾选要删除的数据', { icon: 15, time: 1000, shade: 0.3 });
                return false;
            }
            if($.common.istype(id,'array')){
                id = id.join(',');
            }
            layer.confirm('您确定删除数据吗？', function() {
                $.ajax({
                    beforeSend: function() {
                        layer.load(2);
                    },
                    url: url,
                    type: "POST",
                    async: true,
                    dataType: "json",
                    data: {ids: id, batch: batch},
                    error: function(error) {
                        layer.msg("服务器错误或超时");
                        return false;
                    },
                    success: function(res) {
                        if (res.code == 1) {
                            layCenter.layerMsg(res.msg, 1, function() {
                                layCenter.CreateReload(table_id); //重载表格
                            });
                        } else if(res.code == 2){
                            layer.msg(res.msg, { icon: 15, time: 1500, shade: 0.3, anim: 4 }, function() {
                                layCenter.JumpLogin();
                            });
                        } else {
                            layer.msg(res.msg, { icon: 15, time: 1000, shade: 0.3 });
                        }
                    },
                    complete: function() {
                        layer.closeAll('loading');
                    }
                });
            });
        },

        /**
         * 跳转至登陆页
         * @constructor
         */
        JumpLogin: function(){
            location.href = "{:url('login/login')}";
        },

        /**
         * 上传图片或者文件
         * @param elem 元素
         * @param url 上传urL
         * @param type 类型 ，1图片，2文件
         * @constructor
         */
        Upload: function(elem,url,type) {
            //icon图片上传
            upload.render({
                elem: elem
                ,url: url+'type='+type
                ,done: function(res){
                    //如果上传失败
                    if(res.code > 0){
                        layer.msg('上传失败', { icon: 15, time: 1000, shade: 0.3 });
                        return false;
                    }
                    //上传成功,返回路径
                    return  res.data.src
                }
                ,error: function(){
                    //演示失败状态，并实现重传
                    layer.msg('上传失败', { icon: 15, time: 1000, shade: 0.3 });
                    return false;
                }
            });
        },
        /**
         * 清除redis缓存
         * @param redisKey
         * @param redisHashKey
         * @param clearType
         * @param alertMsg
         * @param retFun
         */
        clearRedisKey: function(redisKey, clearType, redisHashKey, alertMsg, retFun){
            if (typeof(redisKey)=='undefined' || redisKey === '') return;
            redisKey = $.trim(redisKey);
            redisKey = redisKey.replace(/，/g, ',');
            redisKey = redisKey.replace(/\s+/g, '');
            if (redisKey) {
                //clearType = 1;//0 只清除指定key名的缓存（多个用逗号隔开）, 1 清除包含指定key名的缓存, 2 清除某个hashKey的缓存（多个用逗号隔开）
                var data = '';
                if(clearType){
                    switch (clearType) {
                        case 0:
                            data = "key="+redisKey;
                            break;
                        case 1:
                            data = "key="+redisKey;
                            break;
                        case 2:
                            data = "key="+redisKey+"&hashKey="+redisHashKey;
                            break;
                        default:
                            clearType=0;
                            break;
                    }
                    data += "&type="+clearType;
                }
                $.ajax({
                    type:'post',
                    url:"/admin/Cache/clearApiRedisCache",
                    data: data,
                    dataType:'json',
                    success:function(result){
                        var msg = '';
                        if(result.code == 1) {
                            msg = '操作成功';
                        } else {
                            msg = result.msg;
                        }
                        if(retFun) return retFun();
                        if (alertMsg !== false) {
                            alert(msg);
                        } else {
                            return msg;
                        }
                    }
                });
            }
        }
    };


    /**
     * 输出模块(此模块接口是对象)
     */
    exports('layCenter', layCenter);

});